package com.weixing.mall.provider.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.provider.api.model.enums.InOrOutEnum;
import com.weixing.mall.provider.api.model.vo.DeliveryAddressVo;
import com.weixing.mall.provider.api.model.vo.GoodsPointDetailsVo;
import com.weixing.mall.provider.api.model.vo.MemberRpcVo;
import com.weixing.mall.provider.api.service.DeliveryAddressServiceRpc;
import com.weixing.mall.provider.api.service.GoodsFeign;
import com.weixing.mall.provider.api.service.MemberServiceRpc;
import com.weixing.mall.provider.mapper.OrderPointMapper;
import com.weixing.mall.provider.model.domain.OrderPoint;
import com.weixing.mall.provider.model.dto.ExchangeGoodsPointDto;
import com.weixing.mall.provider.model.enums.OrderPointStatusEnum;
import com.weixing.mall.provider.model.query.OrderPointQuery;
import com.weixing.mall.provider.model.vo.OrderPointVo;
import com.weixing.mall.provider.service.IOrderPointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 积分商品兑换订单 服务实现类
 * </p>
 *
 * @author Small
 * @since 2020-05-08
 */
@Service
public class OrderPointServiceImpl extends ServiceImpl<OrderPointMapper, OrderPoint> implements IOrderPointService {
    @Autowired
    private GoodsFeign goodsFeign;
    @Autowired
    private MemberServiceRpc memberServiceRpc;
    @Autowired
    private DeliveryAddressServiceRpc deliveryAddressServiceRpc;
    @Autowired
    private OrderPointMapper orderPointMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result exchangeGoodsPoint(ExchangeGoodsPointDto egpd, Long memberId) {
        if(ObjectUtil.isEmpty(egpd) || egpd.getGoodsPointId() == null||egpd.getCount() == null||egpd.getOrderExpressId() == null){
            return ResultUtil.error("兑换失败");
        }
        //查询会员
        Result memberResult = memberServiceRpc.selectById(memberId);
        if(!memberResult.isSuccess() || memberResult.getData() == null){
            return ResultUtil.error("兑换失败");
        }
        MemberRpcVo mrv = (MemberRpcVo) memberResult.getData();
        //查询积分商品
        Result goodsDetailsVoResult = goodsFeign.selectGoodsPointByGoodsPointId(egpd.getGoodsPointId());
        if(!goodsDetailsVoResult.isSuccess() || goodsDetailsVoResult.getData() == null){
            return ResultUtil.error("兑换失败");
        }
        GoodsPointDetailsVo gpdv = (GoodsPointDetailsVo)goodsDetailsVoResult.getData();
        //查询收货地址
        Result addressVoResult = deliveryAddressServiceRpc.getById(egpd.getOrderExpressId());
        if(!addressVoResult.isSuccess() || addressVoResult.getData() == null){
            return ResultUtil.error("兑换失败");
        }
        DeliveryAddressVo dav = (DeliveryAddressVo)addressVoResult.getData();

        //计算积分总额
        Long totalPointAmount =  gpdv.getPointAmount() * egpd.getCount();
        //扣除积分  inOrOut参数 2代表扣除积分
        Result result = memberServiceRpc.updatePoint(memberId,totalPointAmount, InOrOutEnum.OUT.getValue(),gpdv.getGoodsName(),memberId);
        if(!result.isSuccess() || result.getData() == null||!(Boolean) result.getData()){
            return ResultUtil.error("兑换失败");
        }
        //创建订单
        OrderPoint orderPoint = createOrderPoint(egpd,mrv,gpdv,dav,memberId,totalPointAmount);
        //生成积分兑换订单
        boolean flag = save(orderPoint);
        if(!flag){
            throw new BusinessException("兑换失败");
        }
        return ResultUtil.success("兑换成功");
    }

    private OrderPoint createOrderPoint(ExchangeGoodsPointDto egpd, MemberRpcVo mrv,GoodsPointDetailsVo gpdv,DeliveryAddressVo dav,Long memberId,Long totalPointAmount){
        OrderPoint orderPoint = new OrderPoint();
        orderPoint.setBuyerId(memberId).setBuyer(mrv.getNickName());
        orderPoint.setCount(egpd.getCount()).setAmount(totalPointAmount).setStatus(OrderPointStatusEnum.STATUS_0.getValue());
        orderPoint.setGoodsId(gpdv.getId()).setGoodsName(gpdv.getGoodsName()).setGoodsImg(gpdv.getGoodsImg()).setGoodsPoint(gpdv.getPointAmount());
        orderPoint.setReceiverName(dav.getContactUser()).setReceiverMobile(dav.getContactPhone()).setReceiverAddress(dav.getProvince()+dav.getCity()+dav.getRegion()+dav.getAddrDetail());
        return orderPoint;
    }

    @Override
    public IPage<OrderPointVo> selectOrderPointList(Page page, OrderPointQuery orderPointQuery , Long memberId) {
        //IPage<OrderPoint> orderPointIPage = page(page,new LambdaQueryWrapper<OrderPoint>().eq(OrderPoint::getBuyerId,memberId).orderByDesc(OrderPoint::getCreatedTime));
        return orderPointMapper.selectOrderPointList(page,orderPointQuery,memberId);
    }

    @Override
    public Result updateOrderPointStatus(Long orderPointId, Integer status) {
        if(orderPointId == null){
            return ResultUtil.error("failed");
        }
        LambdaUpdateWrapper lqw = new LambdaUpdateWrapper<OrderPoint>().set(OrderPoint::getStatus,status).eq(OrderPoint::getId,orderPointId);
        return update(lqw)?ResultUtil.success("success"):ResultUtil.error("failed");
    }
}
